package com.stdz.counter.utils;

import com.stdz.counter.core.cache.MeterInfoCache;
import com.stdz.counter.core.constant.ClearLoopType;
import com.stdz.counter.core.constant.ClearMode;
import com.stdz.counter.core.pool.SyncThreadPool;
import com.stdz.counter.dao.MeterInfoDao;
import com.stdz.counter.entity.MeterInfo;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * @author xiaodou
 * @date 2020-09-12 11:02
 */
public class MeterClearHelper {

    @Resource
    private MeterInfoDao meterInfoDao;

    private static MeterClearHelper instance = new MeterClearHelper();

    public static MeterClearHelper getInstance() {
        return instance;
    }

    private MeterClearHelper() {
        ResourceUtil.autowired(this);
    }

    private void grepEnableMeters(List<MeterInfo> meterInfos) {
        if (meterInfos == null || meterInfos.size() == 0) {
            return;
        }
        long timestamp = System.currentTimeMillis();
        Iterator<MeterInfo> iterator = meterInfos.iterator();
        while (iterator.hasNext()) {
            MeterInfo meterInfo = iterator.next();
            ClearMode clearMode = ClearMode.getClearMode(meterInfo.getClearMode());
            if (clearMode == null || clearMode == ClearMode.NO_CLEAR) {
                iterator.remove();
                continue;
            }
            if (MeterHelper.ifClearEnable(meterInfo, timestamp)) {
                continue;
            } else {
                if (meterInfo.getClearLoopType() == ClearLoopType.LOOP_OPERTE.getLoopType()
                        && MeterHelper.ifClearOverTime(meterInfo, timestamp)) {
                    meterInfo.clearOver();
                    meterInfoDao.updateClearOver(meterInfo);
                }
                iterator.remove();
            }

        }
    }

    public void checkClearTask(String comPort) {
        List<MeterInfo> meterInfos = MeterInfoCache.getInstance().getComMeterInfos(comPort);
        grepEnableMeters(meterInfos);
        if (meterInfos == null || meterInfos.size() == 0) {
            return;
        }
        SyncThreadPool.clear(comPort, meterInfos);
    }
}
